#!/bin/sh
# Copyright (C) 2024-2025 KoudaiPC Computer Technologies Co., Ltd.
# script name: huangdi-prepare-sysupgrade.sh
# author: david921518@qq.com

################
# global vars
GLB_WORK_DIR=
GLB_DONE_FILE=
GLB_SYSUPGRADE_ROOT=
GLB_SYSUPGRADE_BAK=
################

whoami=$(which whoami)
if [ x"$whoami" == x ]; then
  user="$USER"
else
  user=$(whoami)
fi

log_kmsg_path="/dev/kmsg"
log_con_path="/dev/tty1"

# 定义日志格式-前缀
log_prefix="[prepare-sysuprade]"
# 定义日志目录和文件名
if [ "$user" == "root" ]; then
  log_file_dir="/var/log/kpc/huangdi"
else
  log_file_dir=~/.local/log/kpc/huangdi
fi
log_file_name="sysupgrade.log"
log_file_path="$log_file_dir/$log_file_name"

function log_init()
{
  # 文件不存在则创建
  if [ ! -d "$log_file_dir" ]; then
    mkdir -p $log_file_dir
    chmod -R 755 $log_file_dir
  fi
  if [ ! -f "$log_file_path" ]; then
    touch $log_file_path
  fi
}

# 定义日志打印格式
function log()
{
  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")
  echo "$curtime $log_prefix $@"
  if [ "$user" == "root" ]; then
    echo "$curtime $log_prefix $@" >>$log_file_path
    #sleep 1
    echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    #sleep 1
    #echo "$curtime $log_prefix [con] $@" >$log_con_path
    #sleep 1
  fi
}

function log_from_file()
{
  tmpfile=$@
  if [ ! -f "$tmpfile" ]; then
    log "no file [$tmpfile] to log"
    return 1
  fi

  declare_i_arr lists
  while IFS= read -r line;
  do
    add_i_arr_el lists "$line"
  done <$tmpfile

  # 定义日志时间格式
  local curtime=$(date "+%Y-%m-%d %H:%M:%S")

  #echo "$curtime $log_prefix $@"
  #echo "$curtime $log_prefix $@" >>$log_file_path
  local i=0
  get_i_arr_indices lists indices
  for i in $indices
  do
    echo "$curtime $log_prefix ${line}"
    echo "$curtime $log_prefix ${line}" >>$log_file_path
  done

  if [ "$user" == "root" ]; then
    #echo "$log_prefix [kmsg] $@" >$log_kmsg_path
    get_i_arr_indices lists indices
    for i in $indices
    do
      echo "$curtime $log_prefix ${line}" >$log_kmsg_path
      [ $(( i%10 )) -ne 9 ] || sleep 1
    done

    #sleep 1
  fi
}

# loop forever to reboot
function force_reboot()
{
  log "force reboot now!"
  while true; do reboot; sleep 9; done
}

# clean up firstboot script
function cleanup_firstboot_script()
{
  local firstboot_file=/etc/zzz-firstboot
  if [ -f $firstboot_file ]; then
    log "rm -f $firstboot_file"
    rm -f $firstboot_file
  fi
}

# fix all kinds of possible broken issues
function fix_possible_broken()
{
  #log "do nothing!!!"
  local is_opkg=$(which opkg)
  if [ x"$is_opkg" == x ]; then
    log "Not ipk package managing system!!!"
  else
    opkg update
    # base tools
    opkg install coreutils-whoami
    opkg install coreutils-realpath
    opkg install curl
    # manipulate partition tools
    opkg install parted
    opkg install losetup
    opkg install resize2fs
    opkg install blkid
    opkg install lsblk
    # upgrade system
    opkg install owut
  fi
}

function get_work_dir()
{
  ################
  # /etc/kpc/sysupgrade/guest/huangdi-prepare-sysupgrade.sh
  # /etc/kpc/sysupgrade/guest/huangdi-sys-upgrade.sh
  # /etc/kpc/sysupgrade/root/etc/rc.local
  # /etc/rc.local
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/guest/huangdi-prepare-sysupgrade.sh
  # /kpcos/distro/huangdi/releases/1.04/targets/x86/64/root/etc/rc.local
  ################

  local real_path=$(realpath $0)
  GLB_WORK_DIR=$(dirname "$real_path")
  log "WORK DIR is [$GLB_WORK_DIR]"

  local done_file="${real_path}_done"
  log "done_file=[$done_file]"
  real_done_file=$(realpath "$done_file")
  log "real_done_file=[$real_done_file]"

  GLB_DONE_FILE="$real_done_file"
  log "GLB_DONE_FILE=[$GLB_DONE_FILE]"

  local sysupgrade_root="$GLB_WORK_DIR/../root"
  log "sysupgrade_root=[$sysupgrade_root]"
  real_sysupgrade_root=$(realpath "$sysupgrade_root")
  log "real_sysupgrade_root=[$real_sysupgrade_root]"

  if [ ! -d $real_sysupgrade_root ]; then
    log "No sysupgrade root dir [$real_sysupgrade_root]."
    exit 1
  fi

  GLB_SYSUPGRADE_ROOT="$real_sysupgrade_root"
  log "GLB_SYSUPGRADE_ROOT=[$GLB_SYSUPGRADE_ROOT]"

  local sysupgrade_bak="$GLB_WORK_DIR/../backup"
  log "sysupgrade_bak=[$sysupgrade_bak]"
  real_sysupgrade_bak=$(realpath "$sysupgrade_bak")
  log "real_sysupgrade_bak=[$real_sysupgrade_bak]"

  log "mkdir -p $real_sysupgrade_bak"
  mkdir -p $real_sysupgrade_bak

  if [ ! -d $real_sysupgrade_bak ]; then
    log "No sysupgrade backup dir [$real_sysupgrade_bak]."
    exit 1
  fi

  GLB_SYSUPGRADE_BAK="$real_sysupgrade_bak"
  log "GLB_SYSUPGRADE_BAK=[$GLB_SYSUPGRADE_BAK]"

  GLB_REBOOT_COUNTER=$GLB_WORK_DIR/reboot_counter
  log "GLB_REBOOT_COUNTER=$GLB_REBOOT_COUNTER"
  if [ ! -f $GLB_REBOOT_COUNTER ]; then
    echo "0" >$GLB_REBOOT_COUNTER
  fi
}

function check_reboot_counter()
{
  local reboot_counter=$(cat $GLB_REBOOT_COUNTER)
  reboot_counter=$((reboot_counter + 1))
  log "reboot counter is [$reboot_counter]"
  if [ $reboot_counter -gt 9 ]; then
    log "reboot too many times, exit now!"
    exit 1
  else
    log "set reboot counter to [$reboot_counter]"
    echo "$reboot_counter" >$GLB_REBOOT_COUNTER
  fi
}

function reset_reboot_counter()
{
  log "reset reboot counter"
  echo "0" >$GLB_REBOOT_COUNTER
}

# save installed packages list
function save_pkg_list()
{
  if [ "$1" == "" ]; then
    log "save_pkg_list() filename is empty, do nothing!"
    return
  fi
  local list_file="$PWD"/$1
  log "save bootstrap packages list to $list_file"
  [ -f $list_file ] || opkg list-installed >$list_file
}

# start kpc-heartbeat
function start_heartbeat()
{
  heartbeat_conf_dir=/etc/kpc
  heartbeat_conf_file=/etc/kpc/heartbeat.conf
  heartbeat_file=/usr/sbin/kpc-heartbeat.sh
  heartbeat_lock=/tmp/kpc-hearbeat.lock
  if [ ! -f $heartbeat_conf_file ]; then
    mkdir -p $heartbeat_conf_dir
    echo 9 >$heartbeat_conf_file
  fi
  if [ -x $heartbeat_file ]; then
    log "start kpc-heartbeat"
    (flock -n $heartbeat_lock -c "($heartbeat_file)")&
  fi
}

# check WAN interface
function check_wan_iface()
{
  local COUNTER=0
  local dev_array="$(ip route | awk '/default/ {print $5}')"
  local iface_dev=$(echo $dev_array | awk '{print $1}')
  while [ "$iface_dev"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get default route device interface, exit now"
      exit 1
    fi
    dev_array="$(ip route | awk '/default/ {print $5}')"
    iface_dev=$(echo $dev_array | awk '{print $1}')
  done

  COUNTER=0
  local WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ip addr show $iface_dev | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1)
  done
  log "WAN IP=[${WAN_IP}]"
}

# check WAN interface
function ubus_check_wan_iface()
{
  local COUNTER=0
  WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  while [ "${WAN_IP}"x == x ]; do
    sleep 1
    COUNTER=$((COUNTER + 1))
    if [ $COUNTER -gt 29 ]; then
      log "Can't get WAN IP address, reboot now"
      force_reboot
    fi
    WAN_IP=$(ubus call network.interface.wan status | grep "address" | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
  done
  log "WAN IP=[${WAN_IP}]"
}

function make_sysupgrade_service()
{
  # generate /etc/zzz-sysupgrade
  zzz_sysupgrade=/etc/zzz-sysupgrade
  sysupgrade_lock=/tmp/.sys-upgrade.lock

  log "make $zzz_sysupgrade"

  sysupgrade_file=$(realpath "$GLB_WORK_DIR/huangdi-sys-upgrade.sh")

  if [ ! -f $sysupgrade_file ]; then
    log "No sys upgrade script $sysupgrade_file"
  fi

  if [ ! -x $sysupgrade_file ]; then
    log "first sys upgrade script $sysupgrade_file is not executive"
  fi

  if [ ! -f $zzz_sysupgrade ]; then
    touch $zzz_sysupgrade
    cat <<EOF >>$zzz_sysupgrade
#!/bin/sh -e

if [ -x $sysupgrade_file ]; then
  (flock -x $sysupgrade_lock -c "$sysupgrade_file")&
fi
EOF
    chmod a+x $zzz_sysupgrade
  else
    real_zzz_sysupgrade=$(realpath $zzz_sysupgrade)
    sed "s#/etc/kpc/sysupgrade/guest/huangdi-sys-upgrade.sh#$sysupgrade_file#g" -i $real_zzz_sysupgrade
    chmod a+x $real_zzz_sysupgrade
  fi
}

function run_backup_all_data()
{
  if [ ! -d $GLB_SYSUPGRADE_BAK ]; then
    log "rm -rf $GLB_SYSUPGRADE_BAK"
    rm -rf $GLB_SYSUPGRADE_BAK

    log "mkdir -p $GLB_SYSUPGRADE_BAK"
    mkdir -p $GLB_SYSUPGRADE_BAK
  fi
  local tmpfile=$(mktemp)
  tar -zcf $tmpfile /etc
  cp -af $tmpfile "$GLB_SYSUPGRADE_BAK"/etc.tgz
  rm -f $tmpfile
}

# 0. init script
log_init
log "[prepare-sysupgrade] START"
cleanup_firstboot_script
fix_possible_broken
get_work_dir
if [ -f $GLB_DONE_FILE ]; then
  log "exist file $GLB_DONE_FILE , exit now"
  exit 1
fi
cd "$GLB_WORK_DIR"
check_reboot_counter
start_heartbeat
#check_wan_iface
ubus_check_wan_iface
save_pkg_list pre_prepare_sysupgrade_pkgs.txt

log "PATH=[$PATH]"

# 1. upgrade current distro to latest point of release
tmpfile=$(mktemp)
/usr/sbin/kpc-upgrade-all-pkgs.sh 2>&1 | tee $tmpfile
log_from_file $tmpfile
rm -f $tmpfile

# 2. Back up any data or configuration information
run_backup_all_data

# 3. Prepare a safe environment for the upgrade
#service micro-evtd stop
#if [ -x /usr/sbin/microapl ]; then
#  /usr/sbin/microapl -a system_set_watchdog off
#fi

# 4. banner
if [ -f "$GLB_SYSUPGRADE_ROOT/etc/banner" ]; then
  log "copy $GLB_SYSUPGRADE_ROOT/etc/banner to /etc/banner"
  cp -f "$GLB_SYSUPGRADE_ROOT"/etc/banner /etc/banner
fi

# 5. /etc
if [ -e "$GLB_SYSUPGRADE_ROOT/etc" ]; then
  log "copy $GLB_SYSUPGRADE_ROOT/etc/* to /etc/"
  #cp -af "$GLB_SYSUPGRADE_ROOT"/etc/* /etc/
  for file in $(ls -A $GLB_SYSUPGRADE_ROOT/etc/); do
    cp -af "$GLB_SYSUPGRADE_ROOT/etc/$file" /etc/
  done
fi

# 6. /lib
if [ -e "$GLB_SYSUPGRADE_ROOT/lib" ]; then
  log "copy $GLB_SYSUPGRADE_ROOT/lib/* to /lib/"
  #cp -af "$GLB_SYSUPGRADE_ROOT"/lib/* /lib/
  for file in $(ls -A $GLB_SYSUPGRADE_ROOT/lib/); do
    cp -af "$GLB_SYSUPGRADE_ROOT/lib/$file" /lib/
  done
fi

# 7. /usr/sbin
if [ -e "$GLB_SYSUPGRADE_ROOT/usr/sbin" ]; then
  log "copy $GLB_SYSUPGRADE_ROOT/usr/sbin/* to /usr/sbin/"
  #cp -af "$GLB_SYSUPGRADE_ROOT"/usr/sbin/* /usr/sbin/
  for file in $(ls -A $GLB_SYSUPGRADE_ROOT/usr/sbin/); do
    cp -af "$GLB_SYSUPGRADE_ROOT/usr/sbin/$file" /usr/sbin/
  done
fi

# 8. generate zzz-sysupgrade based on $GLB_WORK_DIR
make_sysupgrade_service

save_pkg_list post_prepare_sysupgrade_pkgs.txt
touch $GLB_DONE_FILE
sync
#sleep 1

log "[prepare-sysupgrade] EXIT"
#sleep 1

# restart system
reset_reboot_counter
#poweroff
